package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.VibrateUtils;
import com.stark.irremote.lib.base.IrAcRemoteController;
import com.stark.irremote.lib.base.IrConst;
import com.stark.irremote.lib.base.bean.IrRemote;
import com.stark.irremote.lib.base.key.IrAcKey;
import com.stark.irremote.lib.net.IRextReqManager;
import com.stark.irremote.lib.net.bean.IrBrand;
import com.stark.irremote.lib.net.bean.IrRemoteIndex;
import com.stark.irremote.lib.ui.util.IrDialogUtil;

import net.irext.decode.sdk.bean.ACStatus;
import net.irext.decode.sdk.utils.Constants;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityRemoteKtBinding;
import flc.ast.utils.MyIrAcRemoteController;
import flc.ast.utils.SwitchSeekBar;
import stark.common.basic.retrofit.IReqRetCallback;

public class RemoteKtActivity extends BaseAc<ActivityRemoteKtBinding> {

    //-----空调-----
    public static boolean isAdd = false;
    public static IrBrand bean;
    public static IrRemote bean2;
    private Dialog myTipDialog;
    private Dialog myResponseDialog;
    private Dialog myReNameDialog;
    //请求到的遥控器索引对象列表
    private List<IrRemoteIndex> mRemoteIndexList = new ArrayList<>();
    private int mCurRemotePos = 0;
    private MyIrAcRemoteController mAcRemoteController;
    private EditText etDialogRenName;


    @Override
    protected int onCreate() {
        return R.layout.activity_remote_kt;
    }

    @Override
    protected void initView() {
        mDataBinding.ivRemoteKtBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mDataBinding.ivRemoteKtRename.setOnClickListener(this);
        mDataBinding.ivRemoteKtTempReduce.setOnClickListener(this);
        mDataBinding.ivRemoteKtTempAdd.setOnClickListener(this);
        mDataBinding.ivRemoteKtMs.setOnClickListener(this);
//        mDataBinding.ivRemoteKtFs.setOnClickListener(this);
        mDataBinding.ivRemoteKtFx.setOnClickListener(this);
        mDataBinding.ivRemoteKtSf.setOnClickListener(this);
        mDataBinding.ivRemoteKtSource.setOnClickListener(this);
        //给各相关按键绑定对应的按键值对象
        mDataBinding.ivRemoteKtTempReduce.setTag(IrAcKey.TEMP_MINUS);
        mDataBinding.ivRemoteKtTempAdd.setTag(IrAcKey.TEMP_ADD);
        mDataBinding.ivRemoteKtMs.setTag(IrAcKey.MODE);
//        mDataBinding.ivRemoteKtFs.setTag(IrAcKey.WIND_SPEED);
        mDataBinding.ivRemoteKtFx.setTag(IrAcKey.WIND_DIR);
        mDataBinding.ivRemoteKtSf.setTag(IrAcKey.SWEEP_WIND);
        mDataBinding.ivRemoteKtSource.setTag(IrAcKey.POWER);
        if (isAdd) {
            //设置名称状态
            mDataBinding.tvRemoteKtName.setText(bean.name + getString(R.string.kt));
            //下载第一个遥控器码库
            reqRemoteIndexAndDownloadFirst();
        } else {
            mDataBinding.tvRemoteKtName.setText(bean2.name);
            mAcRemoteController = MyIrAcRemoteController.create(bean2);
            if (mAcRemoteController != null) {
                mAcRemoteController.setListener(new MyIrAcRemoteController.IListener() {
                    @Override
                    public void onAcStatusChanged(@NonNull ACStatus status) {
                        updateViewByAcStatus(status);
                    }
                });
            }
        }
        mDataBinding.sbRemoteKtFs.setSeekTouchListenr(new SwitchSeekBar.SeekTouchListener() {
            @Override
            public void touchTop(SeekBar seekBar) {
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleWindSpeedKey1();
            }

            @Override
            public void touchSecond(SeekBar seekBar) {
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleWindSpeedKey2();
            }

            @Override
            public void touchThird(SeekBar seekBar) {
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleWindSpeedKey3();
            }

            @Override
            public void touchEnd(SeekBar seekBar) {
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleWindSpeedKey4();
            }
        });
        //提示弹框
        tipDialog();
        //响应弹框
        responseDialog();
        //重命名弹框
        reNameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivRemoteKtRename://编辑名称
                etDialogRenName.setText(mDataBinding.tvRemoteKtName.getText().toString());
                myReNameDialog.show();
                break;
            case R.id.ivRemoteKtTempReduce://减小温度
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleIrKey(IrAcKey.TEMP_MINUS.getValue());
                break;
            case R.id.ivRemoteKtTempAdd://增加温度
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleIrKey(IrAcKey.TEMP_ADD.getValue());
                break;
            case R.id.ivRemoteKtMs://模式
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleIrKey(IrAcKey.MODE.getValue());
                break;
            case R.id.ivRemoteKtFx://风向(风向跟扫风相关)
                //VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                //mAcRemoteController.handleIrKey(IrAcKey.WIND_DIR.getValue());
                break;
            case R.id.ivRemoteKtSf://扫风
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleIrKey(IrAcKey.SWEEP_WIND.getValue());
                break;
            case R.id.ivRemoteKtSource://电源
                VibrateUtils.vibrate(IrConst.VIBRATE_TIME);
                mAcRemoteController.handleIrKey(IrAcKey.POWER.getValue());
                if (isAdd) {
                    myResponseDialog.show();
                }
                break;
            //提示弹框
            case R.id.ivDialogTipRight://关闭提示弹框
                myTipDialog.dismiss();
                break;
            //响应弹框
            case R.id.tvDialogResOff://无响应
                myResponseDialog.dismiss();
                reqRemoteIndexAndDownloadFirst();
                break;
            case R.id.tvDialogResOn://已响应
                myResponseDialog.dismiss();
                isAdd = false;
                mAcRemoteController.saveRemote(mDataBinding.tvRemoteKtName.getText().toString());
                etDialogRenName.setText(mDataBinding.tvRemoteKtName.getText().toString());
                myReNameDialog.show();
                break;
            //重命名弹框
            case R.id.ivDialogRenameCancel://取消
                myReNameDialog.dismiss();
                break;
            case R.id.ivDialogRenameRight://确定
                String name = etDialogRenName.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(R.string.please_input_name);
                    return;
                }
                myReNameDialog.dismiss();
                mDataBinding.tvRemoteKtName.setText(name);
                mAcRemoteController.updateRemote(mDataBinding.tvRemoteKtName.getText().toString());
                break;
        }
    }

    @Override
    protected void initData() {

    }

    /**
     * 请求获取某一电器某一品牌下的所有的遥控器数据，并下载第一个遥控器的码库文件
     */
    private void reqRemoteIndexAndDownloadFirst() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        IRextReqManager.irextApi().listIndexes(this, bean.categoryId, bean.id, new IReqRetCallback<List<IrRemoteIndex>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<IrRemoteIndex> result) {
                if (!success) {
                    dismissDialog();
                    if (TextUtils.isEmpty(msg)) {
                        msg = getString(R.string.ir_get_data_exception);
                    }
                    IrDialogUtil.showNoRemoteIdxDialog(mContext, msg, () -> finish());
                    return;
                }
                if (result == null || result.size() == 0) {
                    dismissDialog();
                    IrDialogUtil.showNoRemoteIdxDialog(mContext, getString(R.string.ir_no_remote_data), () -> finish());
                    return;
                }
                mRemoteIndexList = result;
                mCurRemotePos = 0;
                downloadRemoteIndexBin(true, mRemoteIndexList.get(mCurRemotePos));
            }
        });
    }

    /**
     * 下载remoteIndex对应的遥控器码库文件
     *
     * @param isShowLoading 当前是否有加载框在显示
     * @param remoteIndex
     */
    private void downloadRemoteIndexBin(boolean isShowLoading, @NonNull IrRemoteIndex remoteIndex) {
        if (!isShowLoading) {
            showDialog(getString(com.stark.common.res.R.string.loading));
        }
        IRextReqManager.irextApi().downloadBin(remoteIndex, new IReqRetCallback<String>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable String binFilePath) {
                dismissDialog();
                if (binFilePath == null) {
                    ToastUtils.showShort(msg);
                    return;
                }
                //码库文件下载成功，则创建对应的控制器
                mAcRemoteController = MyIrAcRemoteController.create(remoteIndex);
                if (mAcRemoteController != null) {
                    mAcRemoteController.setListener(new MyIrAcRemoteController.IListener() {
                        @Override
                        public void onAcStatusChanged(@NonNull ACStatus status) {
                            updateViewByAcStatus(status);
                        }
                    });
                }
            }
        });
    }

    //根据获取的模式设置UI
    private void updateViewByAcStatus(ACStatus status) {
        //电源
        int acPower = status.getAcPower();
        if (acPower == Constants.ACPower.POWER_ON.getValue()) {
            mDataBinding.tvRemoteKtNoOpen.setVisibility(View.INVISIBLE);
        } else if (acPower == Constants.ACPower.POWER_OFF.getValue()) {
            mDataBinding.tvRemoteKtNoOpen.setVisibility(View.VISIBLE);
        }

        // mode模式
        int imgId = R.drawable.azhilen;
        String str = "";
        int mode = status.getAcMode();
        if (mode == Constants.ACMode.MODE_COOL.getValue()) {
            //制冷模式
            imgId = R.drawable.azhilen;
            str = getString(R.string.remote_kt_ms1);

        } else if (mode == Constants.ACMode.MODE_HEAT.getValue()) {
            //制热模式
            imgId = R.drawable.azhire;
            str = getString(R.string.remote_kt_ms2);

        } else if (mode == Constants.ACMode.MODE_AUTO.getValue()) {
            //自动模式
            imgId = R.drawable.azidong;
            str = getString(R.string.remote_kt_ms5);

        } else if (mode == Constants.ACMode.MODE_FAN.getValue()) {
            //扫风模式
            imgId = R.drawable.asongf;
            str = getString(R.string.remote_kt_ms3);

        } else {
            //除湿模式
            imgId = R.drawable.achushi;
            str = getString(R.string.remote_kt_ms4);

        }
        mDataBinding.ivRemoteKtMsIcon.setImageResource(imgId);
        mDataBinding.tvRemoteKtMsName.setText(str);

        // temp温度
        int temp = status.getAcTemp();
        String tempText = String.valueOf(temp + 16);
        if (temp == -1) {
            tempText = "NA";
        }
        mDataBinding.tvRemoteKtTemp.setText(tempText);

        // wind speed风速
        int speed = status.getAcWindSpeed();
        Constants.ACWindSpeed windSpeed = Constants.ACWindSpeed.getSpeedByValue(speed);
        switch (windSpeed) {
            case SPEED_LOW:
                mDataBinding.sbRemoteKtFs.setProgress(33);
                break;
            case SPEED_MEDIUM:
                mDataBinding.sbRemoteKtFs.setProgress(66);
                break;
            case SPEED_HIGH:
                mDataBinding.sbRemoteKtFs.setProgress(100);
                break;
            case SPEED_AUTO:
                mDataBinding.sbRemoteKtFs.setProgress(0);
                break;
        }

        //wind 风向
        int windDir = status.getAcWindDir();
        imgId = R.drawable.ashangxiasaof;
        if (windDir == -1) {
            mDataBinding.ivRemoteKtFx.setVisibility(View.INVISIBLE);
        } else if (windDir == Constants.ACSwing.SWING_OFF.getValue()) {
            imgId = R.drawable.ashangxiasaof;
        } else if (windDir == Constants.ACSwing.SWING_ON.getValue()) {
            imgId = R.drawable.azuoyousaof;
        }
        mDataBinding.ivRemoteKtFxIcon.setImageResource(imgId);

        //扫风开关
        if (windDir == -1) {
            mDataBinding.ivRemoteKtSf.setVisibility(View.INVISIBLE);
        } else {
            mDataBinding.ivRemoteKtSf.setVisibility(View.VISIBLE);
            if (windDir == Constants.ACSwing.SWING_ON.getValue()) {
                imgId = R.drawable.akai;
            } else if (windDir == Constants.ACSwing.SWING_OFF.getValue()) {
                imgId = R.drawable.aguan;
            }
            mDataBinding.ivRemoteKtSfIcon.setImageResource(imgId);
        }
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView close = inflate.findViewById(R.id.ivDialogTipRight);
        close.setOnClickListener(this);
        if (isAdd) {
            myTipDialog.show();
        }
    }

    //响应弹框
    private void responseDialog() {
        myResponseDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_response, null);
        myResponseDialog.setContentView(inflate);
        myResponseDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myResponseDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView resOff = inflate.findViewById(R.id.tvDialogResOff);
        TextView resOn = inflate.findViewById(R.id.tvDialogResOn);
        resOff.setOnClickListener(this);
        resOn.setOnClickListener(this);
    }

    //重命名弹框
    private void reNameDialog() {
        myReNameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myReNameDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myReNameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        etDialogRenName = inflate.findViewById(R.id.etDialogRenameText);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameCancel);
        ImageView right = inflate.findViewById(R.id.ivDialogRenameRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}